<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>书籍评论管理</span>
      </div>
      <div class="filter-container">
        <el-input
          v-model="listQuery.bookName"
          placeholder="书名"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-input
          v-model="listQuery.userName"
          placeholder="用户名"
          style="width: 200px; margin-left: 10px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-select v-model="listQuery.status" placeholder="审核状态" clearable class="filter-item" style="width: 130px; margin-left: 10px;">
          <el-option label="全部" :value="undefined" />
          <el-option label="待审核" :value="0" />
          <el-option label="已通过" :value="1" />
          <el-option label="已屏蔽" :value="2" />
        </el-select>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter" style="margin-left: 10px;">
          搜索
        </el-button>
        <el-button class="filter-item" @click="handleReset" style="margin-left: 10px;">
          重置
        </el-button>
        <el-button type="warning" @click="showSensitiveDialog = true" style="margin-left: 10px;">屏蔽词管理</el-button>
      </div>

      <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="封面" align="center" width="60">
          <template #default="scope">
            <el-image
              v-if="scope.row.bookImg"
              :src="scope.row.bookImg"
              style="width: 40px; height: 60px; object-fit: cover; cursor: pointer;"
              fit="cover"
              :preview-src-list="[]"
              @click="handlePreviewImg(scope.row.bookImg)"
            />
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="书名" prop="bookName" align="center" min-width="120" />
        <el-table-column label="用户" prop="user_name" align="center" min-width="100" />
        <el-table-column label="评分" prop="rating" align="center" width="80">
          <template #default="scope">
            <el-rate v-model="scope.row.rating" :max="5" disabled></el-rate>
          </template>
        </el-table-column>
        <el-table-column label="评论内容" prop="content" align="center" min-width="200">
          <template #default="scope">
            <span>{{ scope.row.content }}</span>
            <el-button v-if="scope.row.status === 2 && scope.row.originalContent" type="text" size="small" @click="showOriginalContent(scope.row)">查看原文</el-button>
          </template>
        </el-table-column>
        <el-table-column label="评论时间" prop="time" align="center" min-width="150">
          <template #default="scope">
            {{ formatDate(scope.row.time) }}
          </template>
        </el-table-column>
        <el-table-column label="审核状态" prop="status" align="center" min-width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">已通过</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="danger">已屏蔽</el-tag>
            <el-tag v-else type="warning">待审核</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220">
          <template #default="scope">
            <el-button type="success" size="small" @click="auditComment(scope.row, 1)" v-if="scope.row.status !== 1">通过</el-button>
            <el-button type="warning" size="small" @click="auditComment(scope.row, 2)" v-if="scope.row.status !== 2">屏蔽</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.pageNum"
        :limit.sync="listQuery.pageSize"
        @pagination="getList"
      />
    </el-card>
    <el-dialog v-model="showSensitiveDialog" title="屏蔽词管理" width="400px">
      <div style="margin-bottom: 16px;">
        <el-input v-model="newSensitiveWord" placeholder="输入新屏蔽词" style="width: 220px; margin-right: 10px;" @keyup.enter="addSensitiveWord"/>
        <el-button type="primary" @click="addSensitiveWord">添加</el-button>
      </div>
      <div>
        <el-tag
          v-for="word in sensitiveWords"
          :key="word"
          closable
          @close="deleteSensitiveWord(word)"
          style="margin: 4px;"
          type="danger"
        >{{ word }}</el-tag>
      </div>
    </el-dialog>
    <el-dialog v-model="originalContentDialogVisible" title="原始评论内容" width="500px">
      <div style="white-space: pre-wrap;word-break: break-all;">{{ originalContentText }}</div>
    </el-dialog>
    <el-dialog
      v-model="previewDialogVisible"
      width="auto"
      top="10vh"
      :show-close="true"
      :close-on-click-modal="true"
    >
      <div style="text-align:center;min-width:300px;min-height:300px;">
        <img
          :src="previewImgUrl"
          :style="{
            maxWidth: '80vw',
            maxHeight: '80vh',
            transform: `scale(${previewImgScale})`,
            transition: 'transform 0.2s'
          }"
          @wheel="handleImgWheel"
          draggable="false"
        />
        <div style="margin-top:10px;color:#888;">滚轮缩放，当前：{{ (previewImgScale*100).toFixed(0) }}%</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/Pagination'
import cloudbase from '@cloudbase/js-sdk'

export default {
  name: 'CommentManage',
  components: { Pagination },
  setup() {
    const listLoading = ref(false)
    const list = ref([])
    const total = ref(0)
    const bookMap = ref({})
    const listQuery = reactive({
      pageNum: 1,
      pageSize: 10,
      bookName: '',
      userName: '',
      status: undefined
    })
    const showSensitiveDialog = ref(false)
    const sensitiveWords = ref([])
    const newSensitiveWord = ref('')
    const originalContentDialogVisible = ref(false)
    const originalContentText = ref('')
    const previewDialogVisible = ref(false)
    const previewImgUrl = ref('')
    const previewImgScale = ref(1)

    // 格式化日期
    const formatDate = (date) => {
      if (!date) return '-'
      const d = new Date(date.$date || date)
      return d.toLocaleString()
    }

 

    // 获取评论列表
    const getList = async () => {
      listLoading.value = true
      try {
        const app = cloudbase.init({ env: "cloud1-2gozbkkk09f11d05" })
        await app.auth().signInAnonymously()
        const res = await app.callFunction({
          name: 'Evalutaion',
          data: {
            action: 'list',
            pageNum: listQuery.pageNum,
            pageSize: listQuery.pageSize,
            userName: listQuery.userName || undefined,
            status: listQuery.status,
            bookName: listQuery.bookName || undefined,
            // bookId: ... // 如果按书名筛选，需先查bookId
          }
        })
        if (res.result && res.result.code === 200) {
          list.value = res.result.data // 直接用云函数返回的
          total.value = res.result.total || list.value.length
        } else {
          ElMessage.error(res.result.message || '获取评论失败')
        }
      } catch (error) {
        console.error('获取评论失败:', error)
        ElMessage.error('获取评论失败')
      } finally {
        listLoading.value = false
      }
    }

    // 处理搜索
    const handleFilter = () => {
      listQuery.pageNum = 1
      getList()
    }

    // 处理重置
    const handleReset = () => {
      listQuery.bookName = ''
      listQuery.userName = ''
      listQuery.status = undefined
      listQuery.pageNum = 1
      getList()
    }

    // 删除评论
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
          type: 'warning'
        })
        const app = cloudbase.init({ env: "cloud1-2gozbkkk09f11d05" })
        await app.auth().signInAnonymously()
        const res = await app.callFunction({
          name: 'Evalutaion',
          data: { action: 'delete', id: row._id }
        })
        if (res.result && res.result.code === 200) {
          ElMessage.success('删除成功')
          getList()
        } else {
          ElMessage.error(res.result.message || '删除失败')
        }
      } catch (error) {
        ElMessage.error('删除失败')
      }
    }

    // 审核/屏蔽评论
    const auditComment = async (row, status) => {
      const app = cloudbase.init({ env: "cloud1-2gozbkkk09f11d05" })
      await app.auth().signInAnonymously()
      const res = await app.callFunction({
        name: 'Evalutaion',
        data: { action: 'audit', id: row._id, status }
      })
      if (res.result && res.result.code === 200) {
        ElMessage.success('操作成功')
        getList()
      } else {
        ElMessage.error(res.result.message || '操作失败')
      }
    }

    // 获取屏蔽词
    const fetchSensitiveWords = async () => {
      const app = cloudbase.init({ env: "cloud1-2gozbkkk09f11d05" })
      await app.auth().signInAnonymously()
      const res = await app.callFunction({
        name: 'Evalutaion',
        data: { action: 'getSensitiveWords' }
      })
      if (Array.isArray(res.result)) {
        sensitiveWords.value = res.result
      } else if (Array.isArray(res.result.data)) {
        sensitiveWords.value = res.result.data
      } else {
        sensitiveWords.value = []
      }
    }

    // 添加屏蔽词
    const addSensitiveWord = async () => {
      const word = newSensitiveWord.value.trim()
      if (!word) return
      const app = cloudbase.init({ env: "cloud1-2gozbkkk09f11d05" })
      await app.auth().signInAnonymously()
      const res = await app.callFunction({
        name: 'Evalutaion',
        data: { action: 'addSensitiveWord', word }
      })
      if (res.result && res.result.code === 200) {
        ElMessage.success('添加成功')
        newSensitiveWord.value = ''
        fetchSensitiveWords()
      } else {
        ElMessage.error(res.result.message || '添加失败')
      }
    }

    // 删除屏蔽词
    const deleteSensitiveWord = async (word) => {
      const app = cloudbase.init({ env: "cloud1-2gozbkkk09f11d05" })
      await app.auth().signInAnonymously()
      const res = await app.callFunction({
        name: 'Evalutaion',
        data: { action: 'deleteSensitiveWord', word }
      })
      if (res.result && res.result.code === 200) {
        ElMessage.success('删除成功')
        fetchSensitiveWords()
      } else {
        ElMessage.error(res.result.message || '删除失败')
      }
    }

    // 弹窗打开时自动加载
    watch(showSensitiveDialog, (val) => {
      if (val) fetchSensitiveWords()
    })

    const showOriginalContent = (row) => {
      originalContentText.value = row.originalContent || ''
      originalContentDialogVisible.value = true
    }

    // 预览方法
    const handlePreviewImg = (url) => {
      previewImgUrl.value = url
      previewImgScale.value = 1
      previewDialogVisible.value = true
    }
    const handleImgWheel = (e) => {
      e.preventDefault()
      let scale = previewImgScale.value
      if (e.deltaY < 0) {
        scale += 0.1
      } else {
        scale -= 0.1
      }
      scale = Math.max(0.2, Math.min(5, scale))
      previewImgScale.value = scale
    }

    onMounted(() => {
      getList();
    })

    return {
      list,
      total,
      listQuery,
      listLoading,
      formatDate,
      handleFilter,
      handleReset,
      handleDelete,
      auditComment,
      getList,
      showSensitiveDialog,
      sensitiveWords,
      newSensitiveWord,
      addSensitiveWord,
      deleteSensitiveWord,
      originalContentDialogVisible,
      originalContentText,
      showOriginalContent,
      previewDialogVisible,
      previewImgUrl,
      previewImgScale,
      handlePreviewImg,
      handleImgWheel
    }
  }
}
</script> 